# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
# ========= 导入数据类 ==============
from basicweb.models import Position, Phase


def get_position_select(request):
    """获取某一个部门下的职位，为下拉框提供数据"""
    # 获取当前的部门编号
    department_id = request.POST.get('department_id')
    # 获取职位
    positions = list(Position.objects.filter(department_id=department_id).values('id', 'name'))
    # 定义集合
    position_list = []
    # 遍历
    for index, value in enumerate(positions):
        position_list.append({'name': value.get('name'), 'value': value.get('id')})
    # 返回
    return JsonResponse({'data': position_list})


def add_position(request):
    """添加职位"""
    # 获取前端传递的数据
    department_id = request.POST.get('department_id')
    position_name = request.POST.get('position_name')
    # 判断当前职位名称是否存在
    is_exists = Position.objects.filter(name=position_name, department_id=department_id).exists()
    # 判断
    if is_exists:
        return JsonResponse({'status': False, 'error': '在当前部门中，输入的职位名称已存在！'})
    try:
        Position.objects.create(name=position_name, department_id=department_id)
        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '添加职位出现未知的错误，具有原因：' + str(e)})


def edit_position(request):
    """修改职位"""
    # 获取前端传递的数据
    department_id = request.POST.get('department_id')
    position_id = request.POST.get('position_id')
    position_name = request.POST.get('position_name')
    # 判断当前职位名称是否存在
    is_exists = Position.objects.filter(name=position_name, department_id=department_id).exists()
    # 判断
    if is_exists:
        return JsonResponse({'status': False, 'error': '在当前部门中，输入的职位名称已存在！'})
    try:
        # 获取当前的职位并修改名称
        obj_position = Position.objects.filter(id=position_id).first()
        obj_position.name = position_name
        obj_position.save()
        # 返回
        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '编辑职位出现未知的错误，具有原因：' + str(e)})


def del_position(request):
    """修改职位"""
    # 获取前端传递的数据
    position_id = request.POST.get('position_id')
    # 判断当前职位下是否挂在培训内容
    is_exists = Phase.objects.filter(position_id=position_id).exists()
    # 判断
    if is_exists:
        return JsonResponse({'status': False, 'error': '当前职位上已挂载培训内容，无法删除！'})
    try:
        # 删除当前职位
        Position.objects.filter(id=position_id).delete()

        # 返回
        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '删除职位出现未知的错误，具有原因：' + str(e)})